<template>
  <div class="prescriptionDetails" v-if="prescription.info" v-loading="formLoading">
    <el-form :model="formData" ref="formDataRefs" class="demo-form-inline" label-position="right" :rules="formRules">
      <el-form-item label="处方编号：" class="itemCol">
        <span>{{ prescription.info['order_sn'] }}</span>
      </el-form-item>
        <div class="orderList">
          <div v-for="(item,index) in prescription.info['order_records']" class="orderItem" :class="{ 'lastItem': (index + 1) % 4 === 0 }">
            <div class="content">
              <div class="xh">{{index + 1}}</div>
              <h3 class="title">{{item['status']}}</h3>
              <div>操作人：{{item['operator_name']}}</div>
              <div>时间：{{item['created_at']}}</div>
            </div>
            <div class="icon">
              <img src="/src/assets/rightBottom.png" alt="">
            </div>
          </div>
        </div>

      <el-form-item label="药态：" class="itemCol" prop="drug_process_id">
        <el-select v-model="formData['drug_process_id']" clearable placeholder="请选择药态" style="width: 240px" :disabled="disabled['drug_process_id']">
          <el-option v-for="item in enumsObj.drugProcess" :key="item.id" :label="item.value" :value="item.id" />
        </el-select>
        <el-button v-if="disabled['drug_process_id']" link type="primary" @click="modifyClick('drug_process_id')">修改药态</el-button>
        <div v-else>
          <el-button link type="primary" @click="confirmEdit('drug_process_id')">保存</el-button>
          <el-button link type="primary" @click="cancelEdit('drug_process_id')">取消</el-button>
        </div>
      </el-form-item>

      <el-form-item label="药房：" class="itemCol" prop="drugstore_id">
        <el-select v-model="formData['drugstore_id']" clearable placeholder="请选择药房" style="width: 240px" :disabled="disabled['drugstore_id']">
          <el-option v-for="item in enumsObj.drugStore" :key="item.id" :label="item.value" :value="item.id" />
        </el-select>
        <el-button v-if="disabled['drugstore_id']" link type="primary" @click="modifyClick('drugstore_id')">修改药房</el-button>
        <div v-else>
          <el-button link type="primary" @click="confirmEdit('drugstore_id')">保存</el-button>
          <el-button link type="primary" @click="cancelEdit('drugstore_id')">取消</el-button>
        </div>
      </el-form-item>

      <el-form-item label="主诉：" class="itemCol" prop="main_appeal">
        <el-input type="textarea" v-model="formData['main_appeal']" show-word-limit style="flex: 1" :disabled="disabled['main_appeal']"></el-input>
        <el-button v-if="disabled['main_appeal']" link type="primary" @click="modifyClick('main_appeal')">修改</el-button>
        <div v-else>
          <el-button link type="primary" @click="confirmEdit('main_appeal')">保存</el-button>
          <el-button link type="primary" @click="cancelEdit('main_appeal')">取消</el-button>
        </div>
      </el-form-item>

      <!-- todo  目前没有现病史 5.7-->
<!--      <el-form-item label="现病史：" class="itemCol">-->
<!--        <el-input type="textarea" v-model="prescription.info['drugstore_id']" show-word-limit style="flex: 1"></el-input>-->
<!--        <el-button link type="primary">修改</el-button>-->
<!--      </el-form-item>-->

      <el-form-item label="辨病：" class="itemCol" prop="diagnosis_illness">
        <el-select v-model="formData['diagnosis_illness']" clearable multiple filterable remote reserve-keyword placeholder="请填写诊断病名" remote-show-suffix
          :remote-method="query => diagnose.remoteMethod(query, 1)" :loading="loading" style="flex: 1;" :disabled="disabled.diagnosis_illness">
          <el-option v-for="item in diagnose.illnessOptions" :key="item.code" :label="item.name" :value="item"></el-option>
        </el-select>
        <el-button v-if="disabled.diagnosis_illness" link type="primary" @click="modifyClick('diagnosis_illness')">修改</el-button>
        <div v-else>
          <el-button link type="primary" @click="confirmEdit('diagnosis_illness')">保存</el-button>
          <el-button link type="primary" @click="cancelEdit('diagnosis_illness')">取消</el-button>
        </div>
      </el-form-item>

      <el-form-item label="辨证：" class="itemCol" prop="diagnosis_disease">
        <el-select v-model="formData['diagnosis_disease']" clearable multiple filterable remote reserve-keyword placeholder="请填写症侯名(选填)"
          remote-show-suffix :remote-method="query => diagnose.remoteMethod(query, 2)" :loading="loading" style="flex: 1;" :disabled="disabled.diagnosis_disease">
          <el-option v-for="item in diagnose.diseaseOptions" :key="item.code" :label="item.name"
            :value="item"></el-option></el-select>
        <el-button link type="primary" @click="modifyClick('diagnosis_disease')" v-if="disabled.diagnosis_disease">修改</el-button>
        <div v-else>
          <el-button link type="primary" @click="confirmEdit('diagnosis_disease')">保存</el-button>
          <el-button link type="primary" @click="cancelEdit('diagnosis_disease')">取消</el-button>
        </div>
      </el-form-item>

      <el-form-item label="" class="itemCol" v-if="formData['prescription_items']">
        <div class="label">Rx：</div>
        <el-table :data="formData['prescription_items']['drugList']" style="width: 100%" :border="true">
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button link type="primary">编辑</el-button>
              <el-button link type="primary">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="drug_name" label="药品名称" width="120" />
          <el-table-column prop="standard_type" label="标准" width="120" />
          <el-table-column prop="unit_name" label="单位" width="120" />
          <el-table-column prop="drug_money" label="单价" width="120" />
          <el-table-column prop="decoction_name" label="特殊煎煮" width="120" />
          <el-table-column prop="drug_num" label="单剂数量" width="120" />
          <el-table-column prop="use_limit" label="剂数" width="120" />
          <el-table-column prop="total_num" label="合剂数量" width="120" />
          <el-table-column prop="total_money" label="金额" width="120" />
        </el-table>
        <el-button link type="primary">新增药品</el-button>
      </el-form-item>

      <el-form-item label="" class="itemCol" v-if="formData['prescription_items']">
        <div class="label">辅料：</div>
        <el-table :data="formData['prescription_items']['auxiliaryList']" style="width: 100%" :border="true">
          <el-table-column prop="type_name" label="操作" width="100">
            <template #default="scope">
              <el-button link type="primary">编辑</el-button>
              <el-button link type="primary">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="detail" label="辅料名称" width="120" />
          <el-table-column prop="order_sn" label="单位" width="120" />
          <el-table-column prop="num" label="单价" width="120" />
          <el-table-column prop="pay_moneys" label="单剂数量" width="120" />
          <el-table-column prop="zip" label="剂数" width="120" />
          <el-table-column prop="zip" label="合剂数量" width="120" />
          <el-table-column prop="zip" label="金额" width="120" />
        </el-table>
        <el-button link type="primary">新增辅料</el-button>
      </el-form-item>
    </el-form>

    <div class="label" style="font-size: 16px;margin: 40px 0 30px 0;">用药说明：</div>
    <el-form :model="formInline" class="demo-form-inline" label-position="right">
      <el-form-item label="用药方法：" class="itemCol">
        <div class="medication">
          <span v-for="(u, uk) in useLimitArr" :key="uk">{{ u }}
            <el-input-number v-if="uk !== useLimitArr.length-1" v-model="formData.use_limit[uk]" :controls="false"
                             controls-position="right" class="mx-4" :disabled="disabled['use_limit']" />
          </span>
          <el-button v-if="disabled['use_limit']" link type="primary" @click="modifyClick('use_limit')">修改</el-button>
          <span v-else>
            <el-button link type="primary" @click="confirmEdit('use_limit')">保存</el-button>
            <el-button link type="primary" @click="cancelEdit('use_limit')">取消</el-button>
          </span>
        </div>
      </el-form-item>
      <el-form-item label="煎煮方式：" class="itemCol">
        <el-radio-group v-model="formData['is_fen']" class="ml-4" :disabled="disabled['is_fen']">
          <el-radio :value="2" size="large">自煎</el-radio>
          <el-radio :value="1" size="large">代煎</el-radio>
        </el-radio-group>
        <el-button v-if="disabled['is_fen']" link type="primary" @click="modifyClick('is_fen')">修改</el-button>
        <div v-else>
          <el-button link type="primary" @click="confirmEdit('is_fen')">保存</el-button>
          <el-button link type="primary" @click="cancelEdit('is_fen')">取消</el-button>
        </div>
      </el-form-item>

      <el-form-item label="医嘱：" class="itemCol">
        <el-input type="textarea" v-model="prescription.info['doctor_advice']" show-word-limit disabled></el-input>
      </el-form-item>

      <el-form-item label="医生签名：" class="itemCol">
        <el-image :src="prescription.info['physician_sign']"></el-image>
      </el-form-item>

      <el-form-item label="药师签名：" class="itemCol">
        <el-image :src="prescription.info['pharmacist_sign']"></el-image>
      </el-form-item>

      <el-form-item label="处方金额：" class="itemCol">
        <el-text><span class="unit">￥</span>{{ prescription.info['prescribe_money'] }}</el-text>
      </el-form-item>

      <el-form-item label="修改备注：" class="itemCol">
        <el-input link type="primaryarea" v-model="formData['remark']" show-word-limit></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import {
    ref,
    nextTick,
    onMounted,
    reactive
  } from 'vue'
  import { prescriptionInfo, upDiagnosis, listUnionProcess, switchDrugstoreProcess, cook, check, update } from '/src/api/orderManage/recipeOrder'
  import { useLimit } from "@/api/drug/drugProcess";
  import { list as diagnoseSearch } from "@/api/diagnose";
  const props = defineProps({
    prescriptionOrderId: { type: String },
    prescriptionId: { type: String },
    enumsObj: { type: Object }
  })
  const prescription = reactive({
    info: {}
  })
  const tableData = ref([])
  const value = ref('')
  const list = ref([]);
  const formLoading = ref(true)
  const loading = ref(false);
  const useLimitTemplateOptions = ref([])
  const useLimitArr = ref([])
  const formData = ref({
    diagnosisArr: []
  })
  const drugstoreList = ref([])
  const drug_type_id = ref()
  const old_drug_type_id = ref()
  const disabled = reactive({
    drug_process_id: true,
    drugstore_id: true,
    main_appeal: true,
    is_fen: true,
    use_limit: true,
    diagnosis_illness: true,
    diagnosis_disease: true
  })
  const formRules = reactive({
    drug_process_id: [
      { required: true, message: '请选择药态' },
    ],
    drugstore_id: [
      { required: true, message: '请选择药房' },
    ],
    main_appeal: [
      { required: true, message: '请输入主诉' },
    ],
    is_fen: [
      { required: true, message: '请选择煎煮方式' },
    ],
    use_limit: [
      { required: true, message: '请完善用药方法' },
    ]
  })
  const formDataRefs = ref()
  const diagnose = reactive({
    diseaseOptions: [],
    illnessOptions: [],
    remoteMethod: async(query, type) => {
      if (query) {
        loading.value = true;
        const res = await diagnoseSearch({
          name: query,
          type
        })
        if (type === 1) {
          diagnose.illnessOptions = res.data.data
        } else {
          diagnose.diseaseOptions = res.data.data
        }
        loading.value = false;
      } else {
        if (type === 1) {
          diagnose.illnessOptions = []
        } else {
          diagnose.diseaseOptions = []
        }
      }
      console.log(diagnose)
    }
  })

  const states = [
    'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida',
    'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine',
    'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada',
    'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma',
    'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah',
    'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
  ];

  // 获取详情
  onMounted(async() => {
    formLoading.value = false
    list.value = states.map((item) => {
      return {
        value: `value:${item}`,
        label: `label:${item}`
      };
    });
    await getUseLimitTemplate()
    await getPrescriptionDetails()
    await listUnionProcessMethod()
    await cookMethod()
    formLoading.value = false
  });

  /**
   * 获取处方详情
   */
  const getPrescriptionDetails = async() => {
    const res = await prescriptionInfo({
      id: props.prescriptionOrderId,
      prescription_id: props.prescriptionId
    })
    prescription.info = JSON.parse(JSON.stringify(res.data))
    const useLimit = useLimitTemplateOptions.value.find(item => item.id === res.data.use_limit_id)
    useLimitArr.value = useLimit.value.split("X");
    formData.value = JSON.parse(JSON.stringify(res.data))
    formData.value.diagnosis_illness = res.data.diagnosis_arr[0] || []
    formData.value.diagnosis_disease = res.data.diagnosis_arr[1] || []
    prescription.info.diagnosis_illness = JSON.parse(JSON.stringify(res.data.diagnosis_arr[0] || []))
    prescription.info.diagnosis_disease = JSON.parse(JSON.stringify(res.data.diagnosis_arr[1] || []))
    diagnose.illnessOptions = res.data.diagnosis_arr[0] || []
    diagnose.diseaseOptions = res.data.diagnosis_arr[1] || []
  }

  /**
   * 获取用法模版
   * @returns {Promise<void>}
   */
  const getUseLimitTemplate = async () => {
    const res = await useLimit();
    useLimitTemplateOptions.value = res.data
  }


  const modifyClick = (column) => {
    disabled[column] = false
  }
  // 取消编辑
  const cancelEdit = (column) => {
    disabled[column] = true
    formData.value[column] = prescription.info[column]
    if (column === "diagnosis_disease") {
      diagnose.diseaseOptions = prescription.info.diagnosis_arr[1] || []
    } else if (column === "diagnosis_illness") {
      diagnose.illnessOptions = prescription.info.diagnosis_arr[0] || []
    }
  }
  // 保存编辑
  const confirmEdit = (column) => {
    formDataRefs.value.validateField([column], async err => {
      if (!err) {
        return true
      } else {
        console.log(column, "column")
        if (column === "drug_process_id") {
          if  (await listUnionProcessMethod()) {
            if (await switchDrugstoreProcessMethod()) {
              await cookMethod()
            }
          }
        } else if (column === "diagnosis_disease") {
          await upDiagnosis({
            id: props.prescriptionOrderId,
            type: "diagnosis_disease",
            content: formData.value['diagnosis_disease']
          })
        } else if (column === "diagnosis_illness") {
          await upDiagnosis({
            id: props.prescriptionOrderId,
            type: "diagnosis_illness",
            content: formData.value['diagnosis_illness']
          })
        } else if (column === "drug_process_id") {

        }
        await getPrescriptionDetails()
        disabled[column] = true
      }
    })
  }

  /**
   * 切换药态列表
   */
  const listUnionProcessMethod = async () => {
    const _formData = formData.value
    const drug_names = []
    let total_initial = 0
    for (const drug of _formData['prescription_items']['drugList']) {
      total_initial += Number(drug?.drug_num) || 0
      drug.decoction_name ? drug_names.push(drug.decoction_name) : null
    }
    const options = {
      "old_drug_process_id": prescription.info.drug_process_id,
      "new_drug_process_id": _formData.drug_process_id,
      "drug_ids": _formData['prescription_items']['drugList'].map(item=>item.drug_id),
      "drug_names": drug_names,
      "total_initial": total_initial
    }
    const res = await listUnionProcess(options)
    if (res.code === 200) {
      const _drugProcess = res.data.find(item=>item.drug_process_id === _formData.drug_process_id)
      const _oldDrugProcess = res.data.find(item=>item.drug_process_id === prescription.info.drug_process_id)
      drugstoreList.value = _drugProcess.drugstoreList
      drug_type_id.value = _drugProcess.drug_type_id
      old_drug_type_id.value = _oldDrugProcess.drug_type_id
    }
    return res.code === 200;
  }

  /**
   * 切换药房
   */
  const switchDrugstoreProcessMethod = async () => {
    const _formData = formData.value
    const options = {
      "prescription_id": props.prescriptionId,
      "old_drug_process_id": prescription.info.drug_process_id,
      "old_drug_type_id": drug_type_id,
      "drug_process_id": _formData.drug_process_id,
      "drug_type_id": drug_type_id,
      "drugstore_id": _formData.drugstore_id,
      "prescription_items": {
        "drugList": _formData['prescription_items']['drugList'],
        "auxiliaryList": _formData['prescription_items']['auxiliaryList']
      },
      "use_limit": {
        "use_limit_id": _formData.use_limit_id,
        "use_limit": _formData.use_limit
      }
    }
    const res = await switchDrugstoreProcess(options)
    return res.code === 200;
  }

  /**
   * 计算煎煮方式金额
   */
  const cookMethod = async () => {
    const _formData = formData.value
    const options = {
      "drug_process_id": _formData.drug_process_id,
      "drug_type_id": drug_type_id.value,
      "drugstore_id": _formData.drugstore_id,
      "use_limit": _formData.use_limit,
      "use_limit_id": _formData.use_limit_id,
      "process_num": _formData?.process?.process_num || 0,
      "drugList": _formData['prescription_items']['drugList'],
    }
    const res = await cook(options)
  }
</script>

<style lang="scss" scoped>
  .row {
    display: flex;
    flex-direction: row;
  }

  ::v-deep .el-form-item__label,
  .label {
    margin-bottom: 0 !important;
    display: flex;
    align-items: center;
    width: 100px;
    vertical-align: middle;
    font-weight: 700;
    font-size: 14px;
    color: #515a6e;
  }

  .marginL20 {
    margin-left: 20px;
  }

  .orderList {
    display: flex;
    text-align: left;
    flex-wrap: wrap;
    background: #FAFAFA;
    border-radius: 4px;
    padding: 20px 10px;
    justify-content: flex-start;
    align-items: flex-start;
  }

  .orderItem {
    max-width: 25%;
    margin-bottom: 10px;
    display: flex;
    align-items: center;

  }

  .orderItem:nth-child(4n + 1) {
    margin-left: 0;
    /* 每行第一个项目不添加左边距 */
  }

  .content {
    width: 100%;
    border: 1px solid #64B4FF;
    border-radius: 4px;
    padding: 15px 30px;
    font-size: 12px;
    background: #EAF5FF;
    color: rgba(0, 0, 0, 0.65);
    position: relative;
    font-family: PingFangSC-Regular;
    min-height: 180px;
    margin: 0 20px 0 40px;
    min-height: 120px;

    .title {
      font-size: 14px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
      margin-bottom: 16px;
    }

    .xh {
      position: absolute;
      width: 26px;
      height: 26px;
      left: 0;
      top: 0;
      color: #fff;
      font-size: 12px;
      background: #028FFF;
      line-height: 24px;
      text-align: center;
      border-radius: 0 0 70% 0;
    }
  }

  .orderItem:last-child .content {
    background: #fcf4f4;
    border: 1px solid #fa5757;

    .xh {
      background: #fa5757;
    }
  }

  .orderItem:last-child img {
    // display: none;
    visibility: hidden;
  }

  .icon {
    flex-shrink: 0;
    // margin-left: 10px;
    /* 不允许图片缩小，保持原始大小 */
  }

  .icon img {
    width: 20px;
    height: 20px;
    // margin: 0 10px;
  }

  /* 每行的最后一个订单项不显示图片 */
  .lastItem .icon {
    // display: none;
    visibility: hidden;
  }

  .medication ::v-deep .el-input {
    margin: 0 12px;
  }

  .unit {
    margin-right: 6px;
  }
</style>
